package com.haiya.user.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.haiya.common.annotation.LoginUser;
import com.haiya.common.constant.CommonConstant;
import com.haiya.common.model.*;
import com.haiya.common.response.CommonRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import com.haiya.user.service.ISysMenuService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author qiaoguoqiang
 */
@RestController
@Api(tags = "菜单模块api")
@Slf4j
@RequestMapping("/menus")
public class SysMenuController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 删除菜单
     * insert into sys_menu
     * (id, parent_id, name, sort, type, tenant_id)
     * value (1, 12, "测试测试", 1, 1, 'webApp')
     * delete from sys_menu where tenant_id = 'webApp' and id = 1;
     * @param id
     */
    @ApiOperation(value = "删除菜单")
    @DeleteMapping("/{id}")
    public CommonRes delete(@PathVariable Long id) {
        boolean b = menuService.removeById(id);
        if (b) {
            return CommonRes.ok("操作成功");
        }
        return CommonRes.error("操作失败");
    }

    /**
     * 为角色配置菜单权限时使用
     * @author qiaoguoqiang
     * @param roleId
     * @return
     */
    @ApiOperation(value = "根据roleId获取对应的菜单")
    @GetMapping("/{roleId}/menus")
    public CommonRes findMenusByRoleId(@PathVariable Long roleId) {
        Set<Long> roleIds = new HashSet<>();
        roleIds.add(roleId);
        //获取该角色对应的菜单
        List<SysMenu> roleMenus = menuService.findByRoles(roleIds);
        //全部的菜单列表
        List<SysMenu> allMenus = menuService.findAll();
        List<Map<String, Object>> authTrees = new ArrayList<>();

        Map<Long, SysMenu> roleMenusMap = roleMenus.stream().collect(Collectors.toMap(SysMenu::getId, SysMenu -> SysMenu));

        for (SysMenu sysMenu : allMenus) {
            Map<String, Object> authTree = new HashMap<>();
            authTree.put("id", sysMenu.getId());
            authTree.put("name", sysMenu.getName());
            authTree.put("pId", sysMenu.getParentId());
            authTree.put("open", true);
            authTree.put("checked", false);
            if (roleMenusMap.get(sysMenu.getId()) != null) {
                authTree.put("checked", true);
            }
            authTrees.add(authTree);
        }
        return CommonRes.ok(authTrees);
    }

    /**
     * 根据角色编码拉取菜单列表
     * 使用了缓存
     * @param roleCodes
     * @return
     */
    @ApiOperation(value = "根据roleCodes获取对应的权限")
    @SuppressWarnings("unchecked")
    @Cacheable(value = "menu", key ="#roleCodes")
    @GetMapping("/{roleCodes}")
    public CommonRes findMenuByRoles(@PathVariable String roleCodes) {
        List<SysMenu> result = null;
        if (StringUtils.isNotEmpty(roleCodes)) {
            Set<String> roleSet = (Set<String>)Convert.toCollection(HashSet.class, String.class, roleCodes);
            result = menuService.findByRoleCodes(roleSet, CommonConstant.PERMISSION);
        }
        return CommonRes.ok(result);
    }

    /**
     * 给角色分配菜单
     * 给角色ID(roleId)批量赋予多个菜单的权限(menuIds)
     * POST {roleId: 6, menuIds: [2,3,4]}
     */
    @ApiOperation(value = "角色分配菜单")
    @PostMapping("/granted")
    public CommonRes setMenuToRole(@RequestBody SysMenu sysMenu) {
        menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
        return CommonRes.ok();
    }

    /**
     * 查询所有菜单[不分页]
     * @return
     */
    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/findAlls")
    public CommonRes findAlls() {
        return CommonRes.ok(menuService.findAll());
    }

    /**
     * 查询所有一级菜单
     * @return
     */
    @ApiOperation(value = "获取菜单以及顶级菜单")
    @GetMapping("/findOnes")
    public CommonRes findOnes() {
        return CommonRes.ok(menuService.findOnes());
    }

    /**
     * 添加菜单 或者 更新
     * POST
     * {
     *     "id": 86,
     *     "parentId": 100,
     *     "name": "test only2222",
     *     "url": "/xxxx",
     *     "sort": 1,
     *     "type": 1,
     *     "tenantId": "webApp"
     * }
     * @param menu
     * @return
     */
    @ApiOperation(value = "新增菜单")
    @PostMapping("saveOrUpdate")
    public CommonRes saveOrUpdate(@RequestBody SysMenu menu) {
        boolean b = menuService.saveOrUpdate(menu);
        if (b) {
            return CommonRes.ok("操作成功");
        }
        return CommonRes.error("操作失败");
    }

    /**
     * 当前登录用户的菜单
     *
     * @return
     */
    @GetMapping("/current")
    @ApiOperation(value = "查询当前用户菜单")
    public CommonRes findMyMenu(@LoginUser SysUser user) {
        List<SysRole> roles = user.getRoles();
        if (CollectionUtil.isEmpty(roles)) {
            return CommonRes.ok(Collections.emptyList());
        }
        List<SysMenu> menus = menuService.findByRoleCodes(roles.parallelStream().map(SysRole::getCode).collect(Collectors.toSet()), CommonConstant.MENU);
        return CommonRes.ok(treeBuilder(menus));
    }

    /**
     * 两层循环实现建树
     *
     * @param sysMenus
     * @return
     */
    public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
        List<SysMenu> menus = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            if (ObjectUtils.equals(-1L, sysMenu.getParentId())) {
                menus.add(sysMenu);
            }
            for (SysMenu menu : sysMenus) {
                if (menu.getParentId().equals(sysMenu.getId())) {
                    if (sysMenu.getSubMenus() == null) {
                        sysMenu.setSubMenus(new ArrayList<>());
                    }
                    sysMenu.getSubMenus().add(menu);
                }
            }
        }
        return menus;
    }
}
